// pages/cureCard/cureCard.js
const app = getApp();
const windowHeight = wx.getSystemInfoSync()['windowHeight'];
const windowWidth = wx.getSystemInfoSync()['windowWidth'];
const db = wx.cloud.database();
var tuwenMax = 99;
var cardsList = [];
Page({

    /**
     * 页面的初始数据
     */
    data: {
        windowHeight: windowHeight - 100,
        removeIndex: -1,
        cardIndex: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this;
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 0
            })
        }
        let today = new Date();
        this.setData({
            month: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][today.getMonth()],
            day: today.getDate(),
            dayOfWeek: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][today.getDay()]
        });
        for ( let i = 0; i < 5; i++ ) {
            this.updateCard();
        }
    },
    updateCard(){
        let that = this;
        let num = Math.floor(Math.random(10)*tuwenMax);
        db.collection("sentencesDB").where({
            num: num
        }).get({
            success: function(res) {
                console.log(res);
                let pic = res.data[0].pic;
                let text = res.data[0].text;
                let like = res.data[0].like;
                let num = res.data[0].num;
                let id = res.data[0]._id;
                let likeNumber = Object.keys(like).length;
                let tuwen = {"pic":pic,"text":text,"likeNumber":likeNumber,num:num,"likeit":app.globalData.openid in like,id:id};
                cardsList.push(tuwen);
                that.setData({cardsList});
                that.summonCardAnimation((Math.random()-0.5)*45,(Math.random()-0.5)*50,cardsList.length-1);
            }
        })
    },
    refreshCard(e){
        this.updateCard();
        let index = e.currentTarget.dataset.index;
        console.log(index);
        cardsList[index]["invisble"] = true;
    },
    touchstart(e){
        this.setData({
            startX: e.changedTouches[0].pageX,
            startY: e.changedTouches[0].pageY,
            cardIndex: e.currentTarget.dataset.index
        });
        console.log(cardsList[this.data.cardIndex]);
    },
    touchmove(e){
        let changeX = e.changedTouches[0].pageX - this.data.startX;
        let changeY = e.changedTouches[0].pageY - this.data.startY;
        let index = this.data.cardIndex;
        this.getAnimation(changeX,changeY,index);
    },
    touchend(e){
        let that = this;
        let changeX = e.changedTouches[0].pageX - this.data.startX;
        let changeY = e.changedTouches[0].pageY - this.data.startY;
        let index = this.data.cardIndex;
        console.log(this.data.cardIndex);
        if ( Math.abs(changeX) <= 100 ) {
            this.getAnimation(0,0,index)
        } else {
            this.getAnimation(changeX*5,changeY,index);
            this.getAnimation(0,0,index+1);
            let removeIndex = that.data.removeIndex + 1;
            that.setData({removeIndex,cardIndex:index+1});
            setTimeout(function(){
                cardsList[index]["invisble"] = true;
                
            },500)
            this.updateCard();
        }
    },
    getAnimation(changeX,changeY,index){
        let angle = changeX / windowWidth * 360 * 0.1;
        let ani = wx.createAnimation({
          delay: 0,
          timingFunction: "ease",
          duration: 500
        }).translateX(changeX).translateY(changeY).rotate(angle).step().export();
        cardsList[index]["animation"] = ani;
        this.setData({cardsList});
    },
    summonCardAnimation(changeX,changeY,index){
        let angle = changeX / windowWidth * 360 * 0.1;
        let ani = wx.createAnimation({
          delay: 1000,
          timingFunction: "ease",
          duration: 1000
        }).translateX(changeX).translateY(changeY).rotate(angle).step().export();
        cardsList[index]["animation"] = ani;
        this.setData({cardsList});
    },
    undo(e){
        let removeIndex = this.data.removeIndex;
        this.getAnimation(0,0,removeIndex);
        cardsList[removeIndex]["invisble"] = false;
        removeIndex -= 1;
        this.setData({removeIndex,cardsList});
    },
    likeit(e){
        let index = this.data.cardIndex;
        let id = cardsList[index].id;
        if ( cardsList[index].likeit ) {
            cardsList[index].likeit = false;
            cardsList[index].likeNumber -= 1; 
            db.collection("sentencesDB").doc(id).get({
                success: function(res) {
                    let like = res.data.like;
                    delete like[app.globalData.openid];
                    db.collection('sentencesDB').doc(id).update({
                        data: {
                            like: db.command.set(like)
                        }
                    });
                }
            })
        }
        else {
            cardsList[index].likeit = true;
            cardsList[index].likeNumber += 1; 
            db.collection('sentencesDB').doc(id).update({
                data: {
                    [`like.${app.globalData.openid}`]: 1
                }
            });
        }
        this.setData({cardsList});
    },
    addDiary(e){
        let index = this.data.cardIndex;
        let today = new Date();
        let url = cardsList[index].pic;
        let file = url.substr(72,url.length);
        console.log(file);
        let pics = {};
        pics[file] = url;
        let timeString = today.valueOf();
        wx.navigateTo({
            url: '../diary/diary',
            success: function(res) {
                res.eventChannel.emit('acceptDataFromOpenerPage',{year:today.getFullYear(),month:today.getMonth()+1,day:today.getDate(),emoji:"愉悦",sentence:cardsList[index].text,images:pics,cloudimage:pics,authorid:app.globalData.openid,publish:false,fixmode: true,visit: false,timeString:timeString});
            }
          })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})